package com.molichuxing.gateway.bff.financial.services.impl;

import com.alibaba.fastjson.JSON;
import com.molichuxing.framework.dto.UploadFileRequestDto;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.DingTalkUtil;
import com.molichuxing.framework.utils.DownloadFileUtil;
import com.molichuxing.framework.utils.EmailUtil;
import com.molichuxing.gateway.bff.basic.services.FileStorageBffService;
import com.molichuxing.gateway.bff.car.entity.request.create.HandoverCheckVo;
import com.molichuxing.gateway.bff.financial.convertor.Convert;
import com.molichuxing.gateway.bff.financial.entity.response.ContractRenegeParamsVo;
import com.molichuxing.gateway.bff.financial.entity.response.ContractVo;
import com.molichuxing.gateway.bff.financial.entity.response.ConvertSendEmailVo;
import com.molichuxing.gateway.bff.financial.services.ContractBffService;
import com.molichuxing.gateway.bff.orders.entity.request.modify.ReturnCarModifyVo;
import com.molichuxing.gateway.bff.orders.entity.request.modify.TradeDeliveryModifyVo;
import com.molichuxing.gateway.utils.NumberToCNUtil;
import com.molichuxing.services.business.dto.request.create.*;
import com.molichuxing.services.business.dto.response.*;
import com.molichuxing.services.business.service.*;
import com.molichuxing.services.contants.OrderStatusConst;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 合同相关bff
 *
 * @author zhaopenghui
 * @date 2019年10月11日
 */
@Service("contractBffService")
public class ContractBffServiceImpl implements ContractBffService {
    private static final Logger logger = LoggerFactory.getLogger(ContractBffServiceImpl.class);
	@Value("${email.account}")
	private String EMAIL_ACCOUNT;

    @Value("${email.password}")
    private String EMAIL_PASSWORD;

	@Value("${profiles.active}")
	private String ACTIVE;

	@Value("${profiles.active.explain}")
	private String ACTIVE_EXPLAIN;


    @Resource
    private ContractService contractService;

	@Resource
	private ContractBizService contractBizService;

	@Resource
	private OrderBizService orderBizService;

	@Resource
	private StoreService storeService;

	@Resource
	private DealerDetailService dealerDetailService;

	@Resource
	private SubcompanyService subcompanyService;

	@Resource
	private UserBizService userBizService;

	@Resource
	private RegionService regionService;

	@Resource
	private CarBizService carBizService;

	@Resource
	private VehicleBizService vehicleBizService;

	@Resource
	private VehicleColorService vehicleColorService;

	@Resource
	private StoreDetailService storeDetailService;

	@Resource
	private DealerService dealerService;
	@Resource
	private FileStorageBffService fileStorageBffService;

	@Resource
	private CarInsuranceBizService carInsuranceBizService;
	@Resource
	private OrderScheduleService orderScheduleService;

	@Resource
	private RiskEmailService riskEmailService;

	@Resource
	private OrderRenegeService orderRenegeService;


	/**
	 * 合同列表
	 *
	 * @param orderCode
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<ContractVo> getContractList(Long orderCode) throws Exception {
		List<ContractDto> contractDtoList = contractService.getContractListByOrderCode(orderCode, null);
		return Convert.toContractVoList(contractDtoList);
	}

	/**
	 * 发送邮件
	 *
	 * @param convertSendEmailVo
	 * @return
	 * @throws Exception
	 */
	@Override
	public Boolean sendEmailAttachments(ConvertSendEmailVo convertSendEmailVo) throws Exception {
		InputStream is = null;
		try {
			String filePath = convertSendEmailVo.getUrl();
			String content = "尊敬的客户您好：附件是您需要的合同相关PDF文件，供下载使用。如有问题，请拨打客服电话400-0311-555。<br/>此邮件为系统自动发送，请勿回复。";
			String email = convertSendEmailVo.getEmail();
			String subject = "【茉莉出行】您有一份合同相关文件，请查收";
			String fileName = convertSendEmailVo.getTitle();
			is = DownloadFileUtil.getInputStreamByUrl(filePath);
			boolean sendBoolean = EmailUtil.sendMail(EMAIL_ACCOUNT, EMAIL_PASSWORD, subject, content, email, fileName,
					is);
			if (sendBoolean) {
				return true;
			} else {
				throw new BizException("发送邮件失败");
			}
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
					is = null;
				}
			}
		}

    }


	/**
	 * 生成合同-提车完成
	 *
	 * @param modifyVo 订单号
	 * @return
	 * @throws Exception
	 */
	@Async
	@Override
	public Boolean createContractByDelivery(TradeDeliveryModifyVo modifyVo) {
		// 需要发送邮件人员的邮箱信息
		List<String> emails = null;
		Boolean ret = false;
		try{
			ret = createContract(modifyVo);
			if(!ret){
				logger.error("订单(" + modifyVo.getOrderCode() + ")生成合同失败,合同服务返回false");
				//邮件
				emails = getEmail(RiskEmailTypeEnum.CONTRACT_GENERATION_FAILED); // getRiskEmailList(RiskEmailEnum.ONE.getValue());
				if(null != emails){
					EmailUtil.sendMail(EMAIL_ACCOUNT, EMAIL_PASSWORD, "合同生成失败", "亲，订单号"+modifyVo.getOrderCode()+"合同生成失败，请介入进一步处理。", emails);
				}else{
					logger.error("生成合同 未配置发送邮件人员的邮箱信息");
				}

				//钉钉
				DingTalkUtil.exceptionSend( "亲，订单号"+modifyVo.getOrderCode()+"合同生成失败，请介入进一步处理。");
			}
		}catch (Exception e){
			logger.error("订单(" + modifyVo.getOrderCode() + ")生成合同失败：", e);
			//邮件
			emails = getEmail(RiskEmailTypeEnum.CONTRACT_GENERATION_FAILED); // getRiskEmailList(RiskEmailEnum.ONE.getValue());
			if(null != emails){
				EmailUtil.sendMail(EMAIL_ACCOUNT, EMAIL_PASSWORD, "合同生成失败", "亲，订单号"+modifyVo.getOrderCode()+"合同生成失败，请介入进一步处理。", emails);
			}else{
				logger.error("生成合同 未配置发送邮件人员的邮箱信息");
			}

			//钉钉
			DingTalkUtil.exceptionSend( "亲，订单号"+modifyVo.getOrderCode()+"合同生成失败，请介入进一步处理。");
		}

		return ret;
	}


	public Boolean createContract(TradeDeliveryModifyVo modifyVo) throws Exception {
		// 根据订单号查询订单信息
		OrderBizDto order = orderBizService.getOrder(modifyVo.getOrderCode());
		if (order == null) {
			String msg = "订单(" + modifyVo.getOrderCode() + ")生成合同失败，订单不存在";
			logger.error(msg);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + msg);
			return false;
		}

		//车辆检验参数json串转实体
		HandoverCheckVo handoverCheckVo = JSON.parseObject(modifyVo.getHandover().getHandoverCheck(),HandoverCheckVo.class);
		if (OrderTypeEnum.EXCLUSIVEL.equals(order.getType())) {
			// 专属订单
			OrderExclusivelBizDto orderBizDto = (OrderExclusivelBizDto) order;
			if (OrderStatusConst.EXCLUSIVEL_UNUSED_STATUS.contains(orderBizDto.getOrderStatus())) {
				String msg = "专属订单(" + modifyVo.getOrderCode() + ")生成合同失败，订单未用车(" + orderBizDto.getOrderStatus().getValue() + ":"
						+ orderBizDto.getOrderStatus().getName() + ")";
				logger.error(msg);
				DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + msg);
				return false;
			}

			//通过下单门店id查询经销商id
			StoreDto storeDto = storeService.getStoreById(orderBizDto.getPlaceStoreId());
			if(null == storeDto || null == storeDto.getDealerId()){
				throw new BizException("门店信息为空");
			}
			//通过经销商id查询分子公司id
			DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(storeDto.getDealerId());
			if(null == dealerDetailDto || null == dealerDetailDto.getSubcompanyId()){
				throw new BizException("经销商详细信息为空");
			}
			//通过分子公司id查询分子公司信息
			SubcompanyDto subcompanyDto = subcompanyService.getSubcompanyNameById(dealerDetailDto.getSubcompanyId());
			if(null == subcompanyDto){
				throw new BizException("分子公司信息为空");
			}
			//根据用户id查询用户信息
			UserBizDto userBizDto = userBizService.getUser(orderBizDto.getUserId());
			if(null == userBizDto){
				throw new BizException("用户信息为空");
			}
			//区id查询省市区
			RegionInfoDto regionInfoDto = regionService.getCityNameByAreaId(userBizDto.getRegionId());
			if(null == regionInfoDto){
				throw new BizException("省市区信息为空");
			}

			//获取车辆信息
			CarDetailBizDto carDetailBizDto = carBizService.getCarDetail(orderBizDto.getCarId());
			if (null == carDetailBizDto) {
				throw new Exception("车辆信息为空");
			}

			// 查询车型信息
			VehicleNameBizDto vehicleBizDto = vehicleBizService.getCarByModel(carDetailBizDto.getVehicleId());
			if (null == vehicleBizDto) {
				throw new Exception("车型信息为空");
			}

			//获取车身颜色
			VehicleColorDto vehicleColorDto = vehicleColorService.getVehicleColorByvehicleColorId(carDetailBizDto.getVehicleColorId());
			if (null == vehicleColorDto) {
				throw new Exception("车身颜色为空");
			}
			//根据门店id查询门店信息
			StoreDetailDto storeDetailDto = storeDetailService.getStoreDetailById(orderBizDto.getPlaceStoreId());
			if (null == storeDetailDto || null == storeDetailDto.getAddress()) {
				throw new Exception("门店信息为空");
			}

			// 查询文件存储配置
			UploadFileRequestDto uploadFileRequestDto = fileStorageBffService.getFileStorageConfig("contract");
			if (uploadFileRequestDto == null) {
				throw new Exception("文件存储配置查询失败");
			}

			List<OrderScheduleDto> orderScheduleDtoList = orderScheduleService.getOrderSchedule(orderBizDto.getOrderCode());
			if (orderScheduleDtoList == null || orderScheduleDtoList.size() <= 0) {
				throw new Exception("排期信息为空");
			}

			//第三者责任险金额
			List<CarInsuranceCommercialDto> carInsuranceCommercialDtoList = carInsuranceBizService.getInsuranceCommercialList(orderBizDto.getCarId());

			ContractExclusivelBizCreateDto createDto = new ContractExclusivelBizCreateDto();

			String goodsName = vehicleBizDto.getSubBrandName()+" "+
					vehicleBizDto.getSeriesName()+" "+
					vehicleBizDto.getYear()+" "+
					vehicleBizDto.getModelName();
			//region 通用条款 和 保证合同 dto

			//通用条款 和 保证合同 dto
			ContractGeneralBizCreateDto contractGeneralBizCreateDto = new ContractGeneralBizCreateDto();
			//甲方
			contractGeneralBizCreateDto.setPartyAName(subcompanyDto.getFullName());
			//甲方id
			contractGeneralBizCreateDto.setPartyAId(subcompanyDto.getId().longValue());
			//甲方联系地址
			contractGeneralBizCreateDto.setPartyAAddress(subcompanyDto.getAddress());
			//乙方
			contractGeneralBizCreateDto.setPartyBName(userBizDto.getRealName());
			//乙方id
			contractGeneralBizCreateDto.setPartyBId(userBizDto.getId().longValue());
			//乙方身份证号
			contractGeneralBizCreateDto.setPartyBCard(userBizDto.getIdNumber());
			//乙方通信地址
			contractGeneralBizCreateDto.setPartyBAddress(regionInfoDto.getProvinceFullName()+regionInfoDto.getCityFullName()+regionInfoDto.getAreaFullName()+userBizDto.getAddress());
			//乙方电话
			contractGeneralBizCreateDto.setPartyBPhone(userBizDto.getPhone());
			//签订日期
			contractGeneralBizCreateDto.setSigningDate(DateUtil.formatDate(LocalDate.now()));
			//是否有担保人 0 ：无，1 ：有   默认0
			contractGeneralBizCreateDto.setIsWarrantor(ContractGuaranteeType.UNCOVERED.getValue());
			//订单code
			contractGeneralBizCreateDto.setOrderCode(orderBizDto.getOrderCode());
			//年月日
			contractGeneralBizCreateDto.setSigningYear(String.valueOf(LocalDate.now().getYear()));
			contractGeneralBizCreateDto.setSigningMonth(String.valueOf(LocalDate.now().getMonthValue()));
			contractGeneralBizCreateDto.setSigningDay(String.valueOf(LocalDate.now().getDayOfMonth()));
			//业务类型(1:订阅里程,2:专属里程,3:经销商)
			contractGeneralBizCreateDto.setBusinessType(ContractBusinessTypeEnum.EXCLUSIVEL.getValue());
			//合同签订时间
			contractGeneralBizCreateDto.setSignedTime(LocalDateTime.now());
			//合同到期日期
			contractGeneralBizCreateDto.setEndTime(orderBizDto.getLeaseExpire());
			//合同生效日期
			contractGeneralBizCreateDto.setEffectiveTime(LocalDate.now());
			//品牌缩写
			contractGeneralBizCreateDto.setBrandChannel(vehicleBizDto.getAbbreviation());
			//每个自然月支付时间
			contractGeneralBizCreateDto.setPayTime(orderScheduleDtoList.get(0).getPayableDate().getDayOfMonth() > 28? "28": String.valueOf(orderScheduleDtoList.get(0).getPayableDate().getDayOfMonth()));
			//endregion

			//region 专用条款 和 补充协议dto
			//专用条款 和 补充协议dto
			ContractSupplementBizCreateDto contractSupplementBizCreateDto = new ContractSupplementBizCreateDto();
			//甲方
			contractSupplementBizCreateDto.setPartyAName(subcompanyDto.getFullName());
			//甲方id
			contractSupplementBizCreateDto.setPartyAId(subcompanyDto.getId().longValue());
			//甲方联系地址
			contractSupplementBizCreateDto.setPartyAAddress(subcompanyDto.getAddress());
			//乙方
			contractSupplementBizCreateDto.setPartyBName(userBizDto.getRealName());
			//乙方id
			contractSupplementBizCreateDto.setPartyBId(userBizDto.getId().longValue());
			//乙方身份证号
			contractSupplementBizCreateDto.setPartyBCard(userBizDto.getIdNumber());
			//乙方通信地址
			contractSupplementBizCreateDto.setPartyBAddress(regionInfoDto.getProvinceFullName()+regionInfoDto.getCityFullName()+regionInfoDto.getAreaFullName()+userBizDto.getAddress());
			//乙方电话
			contractSupplementBizCreateDto.setPartyBPhone(userBizDto.getPhone());
			//签订日期
			contractSupplementBizCreateDto.setSigningDate(DateUtil.formatDate(LocalDate.now()));
			//租赁产品名称  （子品牌名+车系名+年款+车型名称+租期+是否回购+付款方式）
			contractSupplementBizCreateDto.setGoodsName(goodsName);
			//车辆品牌
			contractSupplementBizCreateDto.setBrand(vehicleBizDto.getSubBrandName());
			//车型
			contractSupplementBizCreateDto.setModelName(vehicleBizDto.getSeriesName()+" "+vehicleBizDto.getModelName());
			//车辆生产商

			//车辆颜色
			contractSupplementBizCreateDto.setColorName(vehicleColorDto.getName());
			//车架号
			contractSupplementBizCreateDto.setVin(carDetailBizDto.getVin());
			//车牌号
			contractSupplementBizCreateDto.setLicencePlate(carDetailBizDto.getLicencePlate());
			//交接地点
			contractSupplementBizCreateDto.setDeliveryAddress(storeDetailDto.getAddress());
			//租期
			contractSupplementBizCreateDto.setLease(orderBizDto.getTransportTime());
			//月租金
			contractSupplementBizCreateDto.setCartFee(toMoney(orderBizDto.getRental()));
			//租赁费用总计
			contractSupplementBizCreateDto.setTotalFee(toMoney(orderBizDto.getCartFee()));
			//租赁费用大写
			contractSupplementBizCreateDto.setTotalFeeUpper(NumberToCNUtil.number2CNMontrayUnit(orderBizDto.getCartFee()));
			//TODO 缺少字段 过户费

			//TODO 过户费大写

			//保证金
			contractSupplementBizCreateDto.setDepositFee(toMoney(orderBizDto.getDeposit()));
			//保证金大写
			contractSupplementBizCreateDto.setDepositFeeUpper(NumberToCNUtil.number2CNMontrayUnit(orderBizDto.getDeposit()));
			if(null != orderBizDto.getBuybackAmount()){
				//回购价格
				contractSupplementBizCreateDto.setRepurchaseFee(toMoney(orderBizDto.getBuybackAmount()));
				//回购价格大写
				contractSupplementBizCreateDto.setRepurchaseFeeUpper(NumberToCNUtil.number2CNMontrayUnit(orderBizDto.getBuybackAmount()));
			}
			if(null != orderBizDto.getMinimunGuaranteeAmount()){
				//双方确认保底回购价格 ?
				contractSupplementBizCreateDto.setGuaranteeFee(toMoney(orderBizDto.getMinimunGuaranteeAmount()));
				//最大扣减金额  ?
				BigDecimal depletionFee = orderBizDto.getBuybackAmount().subtract(orderBizDto.getMinimunGuaranteeAmount());
				contractSupplementBizCreateDto.setDepletionFee(toMoney(depletionFee));
			}
			//是否担保
			contractSupplementBizCreateDto.setIsGuarantee("否");
			//是否有担保人 0 ：无，1 ：有
			contractSupplementBizCreateDto.setIsWarrantor(ContractGuaranteeType.UNCOVERED.getValue());
			//待定 还款计划日期
			contractSupplementBizCreateDto.setRepaymentDate(orderScheduleDtoList.get(0).getPayableDate().getDayOfMonth() > 28? "28": String.valueOf(orderScheduleDtoList.get(0).getPayableDate().getDayOfMonth()));
			//年月日
			contractSupplementBizCreateDto.setSigningYear(String.valueOf(LocalDate.now().getYear()));
			contractSupplementBizCreateDto.setSigningMonth(String.valueOf(LocalDate.now().getMonthValue()));
			contractSupplementBizCreateDto.setSigningDay(String.valueOf(LocalDate.now().getDayOfMonth()));
			//专用条款年月日
			contractSupplementBizCreateDto.setDedicatedSigningYear(String.valueOf(LocalDate.now().getYear()));
			contractSupplementBizCreateDto.setDedicatedSigningMonth(String.valueOf(LocalDate.now().getMonthValue()));
			contractSupplementBizCreateDto.setDedicatedSigningDay(String.valueOf(LocalDate.now().getDayOfMonth()));

			//订单id
			contractSupplementBizCreateDto.setOrderId(orderBizDto.getId().toString());
			//订单code
			contractSupplementBizCreateDto.setOrderCode(orderBizDto.getOrderCode());
			//业务类型(1:订阅里程,2:专属里程,3:经销商)
			contractSupplementBizCreateDto.setBusinessType(ContractBusinessTypeEnum.EXCLUSIVEL.getValue());
			//合同签订时间
			contractSupplementBizCreateDto.setSignedTime(LocalDateTime.now());
			//合同到期日期
			contractSupplementBizCreateDto.setEndTime(orderBizDto.getLeaseExpire());
			//合同生效日期
			contractSupplementBizCreateDto.setEffectiveTime(LocalDate.now());
			//邮箱地址
			contractSupplementBizCreateDto.setUserEmail(userBizDto.getEmail());
			//第三者责任险金额
			if(null != carInsuranceCommercialDtoList && carInsuranceCommercialDtoList.size() > 0){
				for (CarInsuranceCommercialDto carInsuranceCommercialDto:carInsuranceCommercialDtoList) {
					if(CarInsuranceNameEnum.THIRD_PARTY_LIABILITY_INSURANCE.getValue().equals(carInsuranceCommercialDto.getName())){
						contractSupplementBizCreateDto.setLiabilityAmount(String.valueOf(toMoney(carInsuranceCommercialDto.getAmount())));
					}
				}
			}
			//endregion

			//region 提车单 和 还车单dto
			//提车单 和 还车单dto
			ContractDeliveryBizCreateDto contractDeliveryBizCreateDto = new ContractDeliveryBizCreateDto();
			BeanUtils.copyProperties(handoverCheckVo,contractDeliveryBizCreateDto);
			//订单code
			contractDeliveryBizCreateDto.setOrderCode(orderBizDto.getOrderCode());
			//交接类型（1：提车，2：还车，3：验车单）
			contractDeliveryBizCreateDto.setHandoverType(OrderHandoverTypeEnum.DELIVERY_OF_VEHICLE.getValue());
			//商品名称
			contractDeliveryBizCreateDto.setGoodsName(goodsName);
			//VIN号码(车架号)
			contractDeliveryBizCreateDto.setVin(carDetailBizDto.getVin());
			//车牌号
			contractDeliveryBizCreateDto.setLicencePlate(carDetailBizDto.getLicencePlate());
			//车辆颜色
			contractDeliveryBizCreateDto.setColorName(vehicleColorDto.getName());
			//租期(合约时长)
			contractDeliveryBizCreateDto.setLease(orderBizDto.getTransportTime());
			//车型名称
			contractDeliveryBizCreateDto.setModelName(vehicleBizDto.getSeriesName()+" "+vehicleBizDto.getModelName());
			//甲方
			contractDeliveryBizCreateDto.setPartyAName(subcompanyDto.getFullName());
			//甲方id
			contractDeliveryBizCreateDto.setPartyAId(subcompanyDto.getId().longValue());
			//乙方（承租人姓名）
			contractDeliveryBizCreateDto.setPartyBName(userBizDto.getRealName());
			//乙方id
			contractDeliveryBizCreateDto.setPartyBId(userBizDto.getId().longValue());
			//丙方（门店名称）
			contractDeliveryBizCreateDto.setPartyCName(storeDto.getShortName());
			//丙方（门店id）
			contractDeliveryBizCreateDto.setPartyCId(storeDetailDto.getStoreId().longValue());
			//乙方身份证号
			contractDeliveryBizCreateDto.setPartyBCard(userBizDto.getIdNumber());
			//承租人联系电话
			contractDeliveryBizCreateDto.setPartyBPhone(userBizDto.getPhone());
			//销售顾问名称
			contractDeliveryBizCreateDto.setEmployeeName(modifyVo.getSalesmanName());
			//提车门店
			contractDeliveryBizCreateDto.setCarStoresAddress(storeDto.getShortName());
			//是否有担保人 0 ：无，1 ：有
			contractDeliveryBizCreateDto.setIsWarrantor(ContractGuaranteeType.UNCOVERED.getValue());
			//公里数（km）
			contractDeliveryBizCreateDto.setMileage(modifyVo.getMileage());
			//车钥
			contractDeliveryBizCreateDto.setCarKeyStatus(modifyVo.getHandover().getKeyNums());
			//汽车外观图
			contractDeliveryBizCreateDto.setCarUrl(modifyVo.getHandover().getCheckUrl());
			//创建时间
			contractDeliveryBizCreateDto.setCreateTime(new Date());
			//修改时间
			contractDeliveryBizCreateDto.setUpdateTime(new Date());
			//签订日期
			contractDeliveryBizCreateDto.setSigningDate(DateUtil.formatDate(LocalDate.now()));
			//合同签订时间
			contractDeliveryBizCreateDto.setSignedTime(LocalDateTime.now());
			//合同到期日期
			contractDeliveryBizCreateDto.setEndTime(orderBizDto.getLeaseExpire());
			//合同生效日期
			contractDeliveryBizCreateDto.setEffectiveTime(LocalDate.now());
			//业务类型(1:订阅里程,2:专属里程,3:经销商)
			contractDeliveryBizCreateDto.setBusinessType(ContractBusinessTypeEnum.EXCLUSIVEL.getValue());

			//endregion


			createDto.setContractCreateEnum(ContractCreateEnum.EXTRACT_VEHICLE);
			createDto.setContractDeliveryBizCreateDto(contractDeliveryBizCreateDto);
			createDto.setContractGeneralBizCreateDto(contractGeneralBizCreateDto);
			createDto.setContractSupplementBizCreateDto(contractSupplementBizCreateDto);
			createDto.setUploadFileRequestDto(uploadFileRequestDto);
			// 添加专属合同
			return contractBizService.createExclusivelContract(createDto);
		} else if (OrderTypeEnum.SUBSCRIBE.equals(order.getType())) {
			// 订阅订单
			OrderSubscribeBizDto orderBizDto = (OrderSubscribeBizDto) order;
			if (OrderStatusConst.SUBSCRIBE_UNUSED_STATUS.contains(orderBizDto.getOrderStatus())) {
				String msg = "订阅订单(" + modifyVo.getOrderCode() + ")生成合同失败，订单未用车(" + orderBizDto.getOrderStatus().getValue() + ":"
						+ orderBizDto.getOrderStatus().getName() + ")";
				logger.error(msg);
				DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + msg);
				return false;
			}

			//通过下单门店id查询经销商id
			StoreDto storeDto = storeService.getStoreById(orderBizDto.getPlaceStoreId());
			if(null == storeDto || null == storeDto.getDealerId()){
				throw new BizException("门店信息为空");
			}
			//通过经销商id查询经销商信息
			DealerDto dealerDto = dealerService.getDealerById(storeDto.getDealerId());
			if(null == dealerDto || null == dealerDto.getFullName()){
				throw new BizException("经销商信息为空");
			}
			//通过经销商id查询分子公司id
			DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(storeDto.getDealerId());
			if(null == dealerDetailDto || null == dealerDetailDto.getSubcompanyId()){
				throw new BizException("经销商详细信息为空");
			}
			//通过分子公司id查询分子公司信息
			SubcompanyDto subcompanyDto = subcompanyService.getSubcompanyNameById(dealerDetailDto.getSubcompanyId());
			if(null == subcompanyDto){
				throw new BizException("分子公司信息为空");
			}
			//根据用户id查询用户信息
			UserBizDto userBizDto = userBizService.getUser(orderBizDto.getUserId());
			if(null == userBizDto){
				throw new BizException("用户信息为空");
			}
			//区id查询省市区
			RegionInfoDto regionInfoDto = regionService.getCityNameByAreaId(userBizDto.getRegionId());
			if(null == regionInfoDto){
				throw new BizException("省市区信息为空");
			}

			//获取车辆信息
			CarDetailBizDto carDetailBizDto = carBizService.getCarDetail(orderBizDto.getCarId());
			if (null == carDetailBizDto) {
				throw new Exception("车辆信息为空");
			}

			// 查询车型信息
			VehicleNameBizDto vehicleBizDto = vehicleBizService.getCarByModel(carDetailBizDto.getVehicleId());
			if (null == vehicleBizDto) {
				throw new Exception("车型信息为空");
			}

			//获取车身颜色
			VehicleColorDto vehicleColorDto = vehicleColorService.getVehicleColorByvehicleColorId(carDetailBizDto.getVehicleColorId());
			if (null == vehicleColorDto) {
				throw new Exception("车身颜色为空");
			}
			//根据门店id查询门店信息
			StoreDetailDto storeDetailDto = storeDetailService.getStoreDetailById(orderBizDto.getPlaceStoreId());
			if (null == storeDetailDto || null == storeDetailDto.getAddress()) {
				throw new Exception("门店信息为空");
			}

			// 查询文件存储配置
			UploadFileRequestDto uploadFileRequestDto = fileStorageBffService.getFileStorageConfig("contract");
			if (uploadFileRequestDto == null) {
				throw new Exception("文件存储配置查询失败");
			}

			String goodsName = vehicleBizDto.getSubBrandName()+" "+
					vehicleBizDto.getSeriesName()+" "+
					vehicleBizDto.getYear()+" "+
					vehicleBizDto.getModelName();

			//region 订阅里程服务合同dto
			ContractMileageBagBizCreateDto contractMileageBagBizCreateDto = new ContractMileageBagBizCreateDto();
			//业务类型(1:订阅里程,2:专属里程,3:经销商)
			contractMileageBagBizCreateDto.setBusinessType(ContractBusinessTypeEnum.SUBSCRIBE.getValue());
			//丙方(经销商)
			contractMileageBagBizCreateDto.setPartyCName(dealerDto.getFullName());
			//丙方id(经销商)
			contractMileageBagBizCreateDto.setPartyCId(dealerDto.getDealerId().longValue());
			//丙方联系地址(经销商)
			contractMileageBagBizCreateDto.setPartyCAddress(dealerDetailDto.getAddress());
			//乙方
			contractMileageBagBizCreateDto.setPartyBName(userBizDto.getRealName());
			//乙方id
			contractMileageBagBizCreateDto.setPartyBId(userBizDto.getId().longValue());
			//乙方身份证号
			contractMileageBagBizCreateDto.setPartyBCard(userBizDto.getIdNumber());
			//乙方通信地址
			contractMileageBagBizCreateDto.setPartyBAddress(regionInfoDto.getProvinceFullName()+regionInfoDto.getCityFullName()+regionInfoDto.getAreaFullName()+userBizDto.getAddress());
			//乙方电话
			contractMileageBagBizCreateDto.setPartyBPhone(userBizDto.getPhone());
			//甲方1名称(资产公司)
			contractMileageBagBizCreateDto.setPartyAOName(subcompanyDto.getFullName());
			//甲方1id(资产公司)
			contractMileageBagBizCreateDto.setPartyAOId(subcompanyDto.getId().longValue());
			//甲方1联系地址(资产公司)
			contractMileageBagBizCreateDto.setPartyAOAddress(subcompanyDto.getAddress());
			//签订日期
			contractMileageBagBizCreateDto.setSigningDate(DateUtil.formatDate(LocalDate.now()));
			//订单code
			contractMileageBagBizCreateDto.setOrderCode(orderBizDto.getOrderCode());
			//车辆型号
			contractMileageBagBizCreateDto.setModelName(vehicleBizDto.getSeriesName()+" "+vehicleBizDto.getModelName());
			//车辆保证金
			contractMileageBagBizCreateDto.setVehicleGuaranteeFee(toMoney(orderBizDto.getDeposit()).toString());
			//订阅服务费里程值(基础里程)
			contractMileageBagBizCreateDto.setSubMileageVal(orderBizDto.getBaseMileage()+"公里");
			//订阅服务费里程有效时长 (单位:天)(用车时长)
			contractMileageBagBizCreateDto.setSubMileageTime((orderBizDto.getLeaseExpire().toEpochDay() - orderBizDto.getLeaseInception().toEpochDay())+"天");
			//订阅服务费费用(单位:元)（商品租车费）
			contractMileageBagBizCreateDto.setSubMileageFee(toMoney((orderBizDto.getRental().add(orderBizDto.getBaseMileagePrice())))+"元");
			//里程服务费里程值(单位:KM)（里程包里程数）
			contractMileageBagBizCreateDto.setMilMileageVal(orderBizDto.getPackageMileage()+"公里");
			//里程服务费里程有效时长 (单位:天)(用车时长)
			contractMileageBagBizCreateDto.setMilMileageTime((orderBizDto.getLeaseExpire().toEpochDay() - orderBizDto.getLeaseInception().toEpochDay())+"天");
			//里程服务费费用(单位:元)（里程包价格）
			contractMileageBagBizCreateDto.setMilMileageFee(toMoney(orderBizDto.getPackageMileagePrice())+"元");
			//赠送里程里程值(单位:KM)（赠送里程）
			contractMileageBagBizCreateDto.setGiveMileageVal(orderBizDto.getGiftMileage()+"公里");
			//赠送里程里程有效时长 (单位天)(用车时长)
			contractMileageBagBizCreateDto.setGiveMileageTime((orderBizDto.getLeaseExpire().toEpochDay() - orderBizDto.getLeaseInception().toEpochDay())+"天");
			//订阅总里程值(单位:KM)(相加)
			contractMileageBagBizCreateDto.setSubTotalMileage((orderBizDto.getGiftMileage()+orderBizDto.getPackageMileage()+orderBizDto.getBaseMileage())+"公里");
			//订阅总费用(单位:元)(总租金)？
			contractMileageBagBizCreateDto.setSubTotalFee(toMoney(orderBizDto.getCartFee())+"元");
			//生效日期年（起租日）
			contractMileageBagBizCreateDto.setStartYear(String.valueOf(orderBizDto.getLeaseInception().getYear()));
			//生效日期月
			contractMileageBagBizCreateDto.setStartMonth(String.valueOf(orderBizDto.getLeaseInception().getMonthValue()));
			//生效日期日
			contractMileageBagBizCreateDto.setStartDay(String.valueOf(orderBizDto.getLeaseInception().getDayOfMonth()));
			//终止日期年（截止日）
			contractMileageBagBizCreateDto.setEndYear(String.valueOf(orderBizDto.getLeaseExpire().getYear()));
			//终止日期月
			contractMileageBagBizCreateDto.setEndMonth(String.valueOf(orderBizDto.getLeaseExpire().getMonthValue()));
			//终止日期日
			contractMileageBagBizCreateDto.setEndDay(String.valueOf(orderBizDto.getLeaseExpire().getDayOfMonth()));
			//合同签订时间
			contractMileageBagBizCreateDto.setSignedTime(LocalDateTime.now());
			//合同到期日期
			contractMileageBagBizCreateDto.setEndTime(orderBizDto.getLeaseExpire());
			//合同生效日期
			contractMileageBagBizCreateDto.setEffectiveTime(LocalDate.now());
			//品牌缩写
			contractMileageBagBizCreateDto.setBrandChannel(vehicleBizDto.getAbbreviation());
			//endregion

			//region 提车单 和 还车单dto
			//提车单 和 还车单dto
			ContractDeliveryBizCreateDto contractDeliveryBizCreateDto = new ContractDeliveryBizCreateDto();
			BeanUtils.copyProperties(handoverCheckVo,contractDeliveryBizCreateDto);
			//订单code
			contractDeliveryBizCreateDto.setOrderCode(orderBizDto.getOrderCode());
			//交接类型（1：提车，2：还车，3：验车单）
			contractDeliveryBizCreateDto.setHandoverType(OrderHandoverTypeEnum.DELIVERY_OF_VEHICLE.getValue());
			//商品名称
			contractDeliveryBizCreateDto.setGoodsName(goodsName);
			//VIN号码(车架号)
			contractDeliveryBizCreateDto.setVin(carDetailBizDto.getVin());
			//车牌号
			contractDeliveryBizCreateDto.setLicencePlate(carDetailBizDto.getLicencePlate());
			//车辆颜色
			contractDeliveryBizCreateDto.setColorName(vehicleColorDto.getName());
			//租期(合约时长)
			contractDeliveryBizCreateDto.setLease(orderBizDto.getTransportTime());
			//车型名称
			contractDeliveryBizCreateDto.setModelName(vehicleBizDto.getSeriesName()+" "+vehicleBizDto.getModelName());
			//甲方
			contractDeliveryBizCreateDto.setPartyAName(subcompanyDto.getFullName());
			//甲方id
			contractDeliveryBizCreateDto.setPartyAId(subcompanyDto.getId().longValue());
			//乙方（承租人姓名）
			contractDeliveryBizCreateDto.setPartyBName(userBizDto.getRealName());
			//乙方id
			contractDeliveryBizCreateDto.setPartyBId(userBizDto.getId().longValue());
			//丙方（门店名称）
			contractDeliveryBizCreateDto.setPartyCName(storeDto.getShortName());
			//丙方（门店id）
			contractDeliveryBizCreateDto.setPartyCId(storeDetailDto.getStoreId().longValue());
			//乙方身份证号
			contractDeliveryBizCreateDto.setPartyBCard(userBizDto.getIdNumber());
			//承租人联系电话
			contractDeliveryBizCreateDto.setPartyBPhone(userBizDto.getPhone());
			//销售顾问名称
			contractDeliveryBizCreateDto.setEmployeeName(modifyVo.getSalesmanName());
			//提车门店
			contractDeliveryBizCreateDto.setCarStoresAddress(storeDto.getShortName());
			//是否有担保人 0 ：无，1 ：有
			contractDeliveryBizCreateDto.setIsWarrantor(ContractGuaranteeType.UNCOVERED.getValue());
			//公里数（km）
			contractDeliveryBizCreateDto.setMileage(modifyVo.getMileage());
			//车钥
			contractDeliveryBizCreateDto.setCarKeyStatus(modifyVo.getHandover().getKeyNums());
			//汽车外观图
			contractDeliveryBizCreateDto.setCarUrl(modifyVo.getHandover().getCheckUrl());
			//创建时间
			contractDeliveryBizCreateDto.setCreateTime(new Date());
			//修改时间
			contractDeliveryBizCreateDto.setUpdateTime(new Date());
			//签订日期
			contractDeliveryBizCreateDto.setSigningDate(DateUtil.formatDate(LocalDate.now()));
			//合同签订时间
			contractDeliveryBizCreateDto.setSignedTime(LocalDateTime.now());
			//合同到期日期
			contractDeliveryBizCreateDto.setEndTime(orderBizDto.getLeaseExpire());
			//合同生效日期
			contractDeliveryBizCreateDto.setEffectiveTime(LocalDate.now());
			//业务类型(1:订阅里程,2:专属里程,3:经销商)
			contractDeliveryBizCreateDto.setBusinessType(ContractBusinessTypeEnum.SUBSCRIBE.getValue());

			//endregion


			ContractSubscribeBizCreateDto createDto = new ContractSubscribeBizCreateDto();
			createDto.setContractCreateEnum(ContractCreateEnum.EXTRACT_VEHICLE);
			createDto.setContractDeliveryBizCreateDto(contractDeliveryBizCreateDto);
			createDto.setContractMileageBagBizCreateDto(contractMileageBagBizCreateDto);
			createDto.setUploadFileRequestDto(uploadFileRequestDto);
			// 添加订阅合同
			return contractBizService.createSubscribeContract(createDto);
		}
		
		return null;
	}


	/**
	 * 整数取整，小数保留两位小数
	 * @param b
	 * @return
	 */
	public BigDecimal toMoney(BigDecimal b) {
		if(new BigDecimal(b.intValue()).compareTo(b)==0){
			return b.setScale(0);
		}else{
			return b.setScale(2);
		}
	}



	/**
	 * 获取邮件人信息
	 * @return
	 */
	private List<String> getEmail(RiskEmailTypeEnum riskEmailTypeEnum){
		List<RiskEmailDto> riskList = riskEmailService.getByType(riskEmailTypeEnum.getValue(),RiskEmailReceiveTypeEnum.EMAIL_RECIPIENT.getValue());
		List<String> list=null;
		if(null != riskList && !riskList.isEmpty()) {
			list=new ArrayList<>();
			for (RiskEmailDto dto : riskList) {
				list.add(dto.getEmail());
			}
		}
		return list;
	}

	/**
	 * 生成还车单-还车完成
	 * 
	 * @param modifyVo
	 * @return
	 */
	@Override
	public Boolean createContractByReturnCar(ReturnCarModifyVo modifyVo) {
		try {
			LocalDateTime dateTime = LocalDateTime.now();
			LocalDate date = LocalDate.now();

			OrderBizDto order = orderBizService.getOrder(modifyVo.getOrderCode());
			Integer carId = null, // 车辆id
					storeId = null, // 门店id
					userId = null; // 用户id
			Long mainOrderCode = null; // 主订单号
			Integer businessType = null;
			Integer lease = null;
			if (OrderTypeEnum.EXCLUSIVEL.equals(order.getType())) {
				// 专属订单还车
				OrderExclusivelBizDto orderExclusivelBizDto = (OrderExclusivelBizDto) order;
				carId = orderExclusivelBizDto.getCarId();
				storeId = orderExclusivelBizDto.getPlaceStoreId();
				userId = orderExclusivelBizDto.getUserId();
				businessType = ContractBusinessTypeEnum.EXCLUSIVEL.getValue();
				lease = orderExclusivelBizDto.getRepaymentPeriod();
			} else if (OrderTypeEnum.SUBSCRIBE.equals(order.getType())) {
				// 订阅订单还车
				OrderSubscribeBizDto orderSubscribeBizDto = (OrderSubscribeBizDto) order;
				carId = orderSubscribeBizDto.getCarId();
				storeId = orderSubscribeBizDto.getPlaceStoreId();
				userId = orderSubscribeBizDto.getUserId();
				businessType = ContractBusinessTypeEnum.SUBSCRIBE.getValue();

				if (orderSubscribeBizDto.getParentOrderCode() != null
						&& orderSubscribeBizDto.getParentOrderCode() > 0L) {
					// 查询主订单信息
					mainOrderCode = orderBizService.getMasterOrderCode(orderSubscribeBizDto.getOrderCode(),
							OrderTypeEnum.SUBSCRIBE);
				}
			} else {
				throw new Exception("订单类型(" + order.getType() + ")异常");
			}

			// 文件上传信息
			UploadFileRequestDto uploadFileRequestDto = fileStorageBffService.getFileStorageConfig("contract");
			if (uploadFileRequestDto == null) {
				throw new Exception("文件存储配置查询失败");
			}
			// 获取车辆信息
			CarDetailBizDto carDetailBizDto = carBizService.getCarDetail(carId);
			if (null == carDetailBizDto) {
				throw new Exception("车辆信息为空");
			}
			// 查询车型信息
			VehicleNameBizDto vehicleBizDto = vehicleBizService.getCarByModel(carDetailBizDto.getVehicleId());
			if (null == vehicleBizDto) {
				throw new Exception("车型信息为空");
			}
			// 获取车身颜色
			VehicleColorDto vehicleColorDto = vehicleColorService
					.getVehicleColorByvehicleColorId(carDetailBizDto.getVehicleColorId());
			if (null == vehicleColorDto) {
				throw new Exception("车身颜色为空");
			}
			// 根据门店id查询门店信息
			StoreDetailDto storeDetailDto = storeDetailService.getStoreDetailById(storeId);
			if (null == storeDetailDto || null == storeDetailDto.getAddress()) {
				throw new Exception("门店信息为空");
			}
			// 通过下单门店id查询经销商id
			StoreDto storeDto = storeService.getStoreById(storeId);
			if (null == storeDto || null == storeDto.getDealerId()) {
				throw new BizException("门店信息为空");
			}
			// 通过经销商id查询经销商信息
			DealerDto dealerDto = dealerService.getDealerById(storeDto.getDealerId());
			if (null == dealerDto || null == dealerDto.getFullName()) {
				throw new BizException("经销商信息为空");
			}
			// 通过经销商id查询分子公司id
			DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(storeDto.getDealerId());
			if (null == dealerDetailDto || null == dealerDetailDto.getSubcompanyId()) {
				throw new BizException("经销商详细信息为空");
			}
			// 通过分子公司id查询分子公司信息
			SubcompanyDto subcompanyDto = subcompanyService.getSubcompanyNameById(dealerDetailDto.getSubcompanyId());
			if (null == subcompanyDto) {
				throw new BizException("分子公司信息为空");
			}
			// 根据用户id查询用户信息
			UserBizDto userBizDto = userBizService.getUser(userId);
			if (null == userBizDto) {
				throw new BizException("用户信息为空");
			}
			ContractDeliveryBizCreateDto contractDeliveryBizCreateDto = new ContractDeliveryBizCreateDto();

			// 车辆检验参数json串转实体
			HandoverCheckVo handoverCheckVo = JSON.parseObject(modifyVo.getHandover().getHandoverCheck(),
					HandoverCheckVo.class);
			if (handoverCheckVo == null) {
				throw new Exception("车辆检验参数为空");
			}
			BeanUtils.copyProperties(handoverCheckVo, contractDeliveryBizCreateDto);
			// 订单code
			contractDeliveryBizCreateDto.setOrderCode(modifyVo.getOrderCode());
			// 交接类型（1：提车，2：还车，3：验车单）
			contractDeliveryBizCreateDto.setHandoverType(OrderHandoverTypeEnum.TRANSFER_VEHICLE.getValue());
			// 商品名称
			contractDeliveryBizCreateDto
					.setGoodsName(vehicleBizDto.getSubBrandName() + " " + vehicleBizDto.getSeriesName() + " "
							+ vehicleBizDto.getYear() + " " + vehicleBizDto.getModelName());
			// VIN号码(车架号)
			contractDeliveryBizCreateDto.setVin(carDetailBizDto.getVin());
			// 车牌号
			contractDeliveryBizCreateDto.setLicencePlate(carDetailBizDto.getLicencePlate());
			// 车辆颜色
			contractDeliveryBizCreateDto.setColorName(vehicleColorDto.getName());
			// 租期(合约时长)
			contractDeliveryBizCreateDto.setLease(lease);
			// 车型名称
			contractDeliveryBizCreateDto
					.setModelName(vehicleBizDto.getSeriesName() + " " + vehicleBizDto.getModelName());
			// 甲方
			contractDeliveryBizCreateDto.setPartyAName(subcompanyDto.getFullName());
			// 甲方id
			contractDeliveryBizCreateDto.setPartyAId(subcompanyDto.getId().longValue());
			// 乙方（承租人姓名）
			contractDeliveryBizCreateDto.setPartyBName(userBizDto.getRealName());
			// 乙方id
			contractDeliveryBizCreateDto.setPartyBId(userBizDto.getId().longValue());
			// 丙方（门店名称）
			contractDeliveryBizCreateDto.setPartyCName(storeDto.getShortName());
			// 丙方（门店id）
			contractDeliveryBizCreateDto.setPartyCId(storeDetailDto.getStoreId().longValue());
			// 乙方身份证号
			contractDeliveryBizCreateDto.setPartyBCard(userBizDto.getIdNumber());
			// 承租人联系电话
			contractDeliveryBizCreateDto.setPartyBPhone(userBizDto.getPhone());
			// 销售顾问名称
			contractDeliveryBizCreateDto.setEmployeeName(modifyVo.getSalesmanName());
			// 提车门店
			contractDeliveryBizCreateDto.setCarStoresAddress(storeDto.getShortName());
			// 是否有担保人 0 ：无，1 ：有
			contractDeliveryBizCreateDto.setIsWarrantor(ContractGuaranteeType.UNCOVERED.getValue());
			// 公里数（km）
			contractDeliveryBizCreateDto.setMileage(modifyVo.getMileage());
			// 车钥
			contractDeliveryBizCreateDto.setCarKeyStatus(modifyVo.getHandover().getKeyNums());
			// 汽车外观图
			contractDeliveryBizCreateDto.setCarUrl(modifyVo.getHandover().getCheckUrl());
			// 创建时间
			contractDeliveryBizCreateDto.setCreateTime(new Date());
			// 修改时间
			contractDeliveryBizCreateDto.setUpdateTime(new Date());
			// 签订日期
			contractDeliveryBizCreateDto.setSigningDate(DateUtil.formatDate(date));
			// 合同签订时间
			contractDeliveryBizCreateDto.setSignedTime(dateTime);
			// 合同到期日期
			contractDeliveryBizCreateDto.setEndTime(date);
			// 合同生效日期
			contractDeliveryBizCreateDto.setEffectiveTime(date);
			// 业务类型(1:订阅里程,2:专属里程,3:经销商)
			contractDeliveryBizCreateDto.setBusinessType(businessType);

			// 订阅是否续订还车主订单号
			contractDeliveryBizCreateDto.setMainOrderCode(mainOrderCode);

			Boolean rst = false;
			if (OrderTypeEnum.EXCLUSIVEL.equals(order.getType())) {
				// 专属订单还车
				ResponseResult<Boolean> result = contractBizService.createDelivery(contractDeliveryBizCreateDto,
						uploadFileRequestDto);
				if (result != null && result.getData() != null) {
					rst = result.getData();
				}
			} else if (OrderTypeEnum.SUBSCRIBE.equals(order.getType())) {
				// 订阅
				ContractSubscribeBizCreateDto createDto = new ContractSubscribeBizCreateDto();
				createDto.setContractCreateEnum(ContractCreateEnum.RETURN_VEHICLE);
				createDto.setContractDeliveryBizCreateDto(contractDeliveryBizCreateDto);
				createDto.setUploadFileRequestDto(uploadFileRequestDto);

				rst = contractBizService.createSubscribeContract(createDto);
			}

			if (!rst) {
				logger.error("[createContractByReturnCar]订单(" + modifyVo.getOrderCode()
						+ ")生成还车单失败，接口返回false");
				// 钉钉
				DingTalkUtil.exceptionSend("亲，订单号" + modifyVo.getOrderCode() + "还车单生成失败，请介入进一步处理。");
			}
		} catch (Exception e) {
			logger.error("[createContractByReturnCar]订单(" + modifyVo.getOrderCode() + ")生成还车单失败:", e);
			// 钉钉
			DingTalkUtil.exceptionSend("亲，订单号" + modifyVo.getOrderCode() + "还车单生成失败，请介入进一步处理。");
		}
		return true;
	}

	/**
	 * 查询退租解除协议参数信息
	 *
	 * @param orderCode 订单号
	 * @param userId    用户id
	 * @return
	 */
	@Override
	public ContractRenegeParamsVo getContractRenegeParams(Long orderCode, Integer userId, boolean selectMainContract) throws Exception {
		ContractRenegeParamsVo result = new ContractRenegeParamsVo();

		Integer storeId = null;
		// 查询订单信息
		OrderExclusivelBizDto orderExclusivel = (OrderExclusivelBizDto) orderBizService.getOrder(orderCode);
		if (orderExclusivel == null) {
			logger.error("[getContractRenegeParams]订单({})不存在", orderCode);
			throw new BizException("用户订单异常");
		} else if (!orderExclusivel.getUserId().equals(userId)) {
			logger.error("[getContractRenegeParams]订单用户({})和查询用户({})不一致", orderExclusivel.getUserId(), userId);
			throw new BizException("用户订单异常");
		} else if (orderExclusivel.getCarId() == null || orderExclusivel.getCarId() <= 0) {
			return null;
		}
		storeId = orderExclusivel.getPlaceStoreId();
		orderExclusivel = null;

		// 查询退租信息
		OrderRenegeDto orderRenege = orderRenegeService.getEffectiveRenege(orderCode);
		if (orderRenege == null) {
			logger.error("[getContractRenegeParams]订单({})不存在退租", orderCode);
			throw new BizException("用户订单异常");
		}
		result = Convert.toContractRenegeParamsVo(result, orderRenege);
		orderRenege = null;
		// 查询用户信息
		UserBizDto user = userBizService.getUser(userId);
		if (user == null) {
			logger.error("[getContractRenegeParams]用户({})不存在", userId);
			throw new BizException("用户订单异常");
		}
		result = Convert.toContractRenegeParamsVo(result, user);
		user = null;
		if (selectMainContract) {
			// 查询主合同信息
			List<ContractDto> contracts = contractService.getContractByOrderCode(orderCode, ContractTypeEnum.COMMON_CONTRACT.getValue());
			if (contracts == null || contracts.isEmpty()) {
				logger.error("[getContractRenegeParams]订单({})主合同不存在", orderCode);
				throw new BizException("用户订单异常");
			}
			for (ContractDto contract : contracts) {
				if (contract.getContractType() == ContractTypeEnum.COMMON_CONTRACT.getValue()) {
					result = Convert.toContractRenegeParamsVo(result, contract);
					break;
				}
			}
			contracts = null;
		}

		//通过下单门店id查询经销商id
		StoreDto storeDto = storeService.getStoreById(storeId);
		if (null == storeDto || null == storeDto.getDealerId()) {
			logger.error("[getContractRenegeParams]门店({})信息为空", storeId);
			throw new BizException("用户订单异常");
		}
		//通过经销商id查询分子公司id
		DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(storeDto.getDealerId());
		if (null == dealerDetailDto || null == dealerDetailDto.getSubcompanyId()) {
			logger.error("[getContractRenegeParams]经销商({})详细信息为空", storeDto.getDealerId());
			throw new BizException("用户订单异常");
		}
		//通过分子公司id查询分子公司信息
		SubcompanyDto subcompanyDto = subcompanyService.getSubcompanyNameById(dealerDetailDto.getSubcompanyId());
		if (null == subcompanyDto) {
			logger.error("[getContractRenegeParams]分子公司({})信息为空", dealerDetailDto.getSubcompanyId());
			throw new BizException("用户订单异常");
		}
		result = Convert.toContractRenegeParamsVo(result, subcompanyDto);
		// 签订时间
		result.setSignedDate(DateUtil.formatDate(LocalDate.now(), "yyyy年MM月dd日"));

		return result;
	}

	/**
	 * 生成退租解除协议
	 *
	 * @param orderCode 订单号
	 * @param userId    用户id
	 * @return
	 * @throws Exception
	 */
	@Override
	@Async
	public Boolean createContractByRenege(Long orderCode, Integer userId) throws Exception {
		Boolean result = true;
		try {
			ContractRenegeParamsVo params = this.getContractRenegeParams(orderCode, userId, false);
			if (params == null) {
				return true;
			}
			ContractRenegeBizCreateDto createDto = new ContractRenegeBizCreateDto();
			BeanUtils.copyProperties(params, createDto);
			createDto.setPartyA(params.getPartyAName2());
			createDto.setSignedTime(LocalDateTime.now());
			createDto.setOrderCode(orderCode);

			// 文件上传信息
			UploadFileRequestDto uploadFileRequestDto = fileStorageBffService.getFileStorageConfig("contract");
			if (uploadFileRequestDto == null) {
				throw new Exception("文件存储配置查询失败");
			}

			// 生成解除协议
			if (!contractBizService.createRenege(createDto, uploadFileRequestDto)) {
				logger.error("[createContractByRenege]订单(" + orderCode
						+ ")生成解除协议失败，接口返回false");
				// 钉钉
				DingTalkUtil.exceptionSend("亲，订单号" + orderCode + "生成解除协议失败，请介入进一步处理。");
			}
		} catch (Exception e) {
			logger.error("[createContractByRenege]订单(" + orderCode + ")生成解除协议失败:", e);
			// 钉钉
			DingTalkUtil.exceptionSend("亲，订单号" + orderCode + "解除协议生成失败，请介入进一步处理。");

		}


		return result;
	}
}
